package ajaxjs.net;
import java.io.UnsupportedEncodingException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.net.URLDecoder;
import ajaxjs.Constant;
/**
 * 请求类
 * @author frank
 */
public class Request {
	/**
	 * 设定请求编码
	 * @param request
	 * @param response
	 */
	public static void setUTF8(HttpServletRequest request, HttpServletResponse response){
		if(request != null){
			try {
				request.setCharacterEncoding("UTF-8");
			} catch (UnsupportedEncodingException e) {}
		}
		if(response != null)response.setCharacterEncoding("UTF-8");
	}	
	
	/**
	 * 获取请求的参数，如果没有这个参数会被记录下来。
	 * @param request
	 * @param key
	 * @return
	 */
	public static String get(HttpServletRequest request, String key) {
		String value = null;
		
		try {
			value = request.getParameter(key);
			if (value == null || value.equals("")){
				request.setAttribute(Constant.json_Err_KeyName, String.format("请求没有带有 %s 参数或者没有值！", key));
			}
		} catch (Exception e) {
			if(request == null)
				System.out.println(String.format(Constant.missingArgument, "request"));
			
			if(key == null)
				System.out.println(String.format(Constant.missingArgument, "key"));
			
			e.printStackTrace();
		}

		return value;
	}
	
	public static void main(String[] args){
		get(null, null);
	}
	
	/**
	 * 请求参数中有可能有中文的，使用该方法
	 * @param req
	 * @param key
	 * @return
	 */
	public static String getChinese(HttpServletRequest req, String key) {
		String Chinese = get(req, key);
		
		try {
			return new String(Chinese.getBytes("ISO8859_1"), "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			return null;
		}
	}
	
	/**
	 * 获取参数，并自动从字符串转换为 Java 类型，如 "true"--> true,"123"--> 123,"null"-->null
	 * @param req
	 * @param key
	 * @param isTypeCovernt
	 * @return
	 */
	public static Object get(HttpServletRequest req, String key, boolean isTypeCovernt) {
		String value = get(req, key);
		
		if("null".equals(value))return null;
		
		int int_value = Integer.parseInt(value);
		Integer Int_value = (Integer)int_value;
		
		if(Int_value.toString().equals(value)){
			return int_value;
		}else{
			return value;
		}
	}
	
	/**
	 * 获取 id 参数，返回 int 类型
	 * @param request
	 * @return
	 */
	public static int getId(HttpServletRequest request){
		return (Integer)get(request, "id", true);
	}
	
	/**
	 * 获取 id 参数，如果没有传入 id，返回默认 defaultId。返回 int 类型
	 * @param request
	 * @param key
	 * @param defaultId
	 * @return
	 */
	public static int getIdwithDefaultId(HttpServletRequest request, String key, int defaultId){
		int id = 0;
		String idStr = request.getParameter(key);
		id = idStr == null || idStr.equals("") ? defaultId : Integer.parseInt(idStr);
		return id;		
	}	
	
	/**
	 * 获取本页 URL
	 * @return
	 */
	public static String getCurrentPage_url(HttpServletRequest request){
		int serverPort = request.getServerPort();
		String currentPage_url = request.getScheme() + "://" + request.getServerName();
		if(serverPort != 80){
			currentPage_url += ":" + serverPort;
		}
		currentPage_url += request.getRequestURI() + "?" + request.getQueryString();
		
		return currentPage_url;
	}
	
	/**
	 * 获取客户端请求的参数和值
	 * @param request
	 * @return
	 */
	public static Map<String, String> getClient_Data(HttpServletRequest request){
		Map<String, String> data = new HashMap<String, String>();
		String paramName = "", value = "";

		Enumeration<?> enu = request.getParameterNames();
		while (enu.hasMoreElements()) {
			paramName = (String)enu.nextElement();
			
//			try{
//				value = java.net.URLEncoder.encode(request.getParameter(paramName), "UTF-8");
//			}catch(java.io.UnsupportedEncodingException e){}
			
			value = request.getParameter(paramName);
			
			try {
				value = new String(value.getBytes("ISO-8859-1"), "UTF-8");
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
			
//			System.out.println(paramName +":"+ request.getParameter(paramName));
//			System.out.println(paramName +":"+ value);
			data.put(paramName, value);
		}
		
		return data;
	}
	
	/**
	 * 获取客户端请求的参数和值，但返回字符串
	 * @param request
	 * @param isWithQuery
	 * @param ignoreField 忽略的字段
	 * @return
	 */
	public static String getClient_Data(HttpServletRequest request, boolean isWithQuery, String ignoreField){
		Map<String, String> data = getClient_Data(request);

		String str = isWithQuery ? "?" : "";
		int i = 0;
		
		for(String item : data.keySet()){
			if(ignoreField != null && ignoreField.equals(item))continue;
			if(i++ != 0)str += "&";
			str += item + "=" + data.get(item);  
		} 
		
		if(str.equals("?")){
			return "";
		}

		return str;
	}
	
	/**
	 * 获取客户端请求的参数和值，但返回字符串
	 * @param request
	 * @param isWithQuery
	 * @return
	 */
	public static String getClient_Data(HttpServletRequest request, boolean isWithQuery){
		return getClient_Data(request, isWithQuery, null);
	}
	
	/**
	 * servlet 获取 put 提交的参数
	 * http://my.oschina.net/dxqr/blog/138444
	 * @return
	 */
	public static String getPutRequest(HttpServletRequest request){
		if(!"PUT".endsWith(request.getMethod())){
			System.out.println("你的不是 PUT 请求，无须该补丁啊");
			return null;
		}
		
		String str = null;

		try {
			str = ajaxjs.Util.readStream(request.getInputStream());
		} catch (IOException e) {
			System.out.println("获取 request 流失败！");
			e.printStackTrace();
		}
		
		return str;
	}
 
	public static Map<String, String> getPutRequest(String str){
		 try {
			str = URLDecoder.decode(str, "UTF-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		
		Map<String, String> hash = new HashMap<String, String>();
		String[] arr = str.split("&"), itemPairs;
		
		for(String item : arr){
			itemPairs = item.split("=");
			hash.put(itemPairs[0], itemPairs[1]);
		}
		
		return hash;
	}
	
	/**
	 * 输入一个相对地址，补充成为绝对地址
	 * @param request
	 * @param relativePath
	 * @return 绝对地址
	 */
	public static String Mappath(HttpServletRequest request, String relativePath){
		return request.getServletContext().getRealPath(relativePath);
	}
}
